#include "previewscr.h"
#include <QPixmap>
#include <QPainter>
#include <QPen>
#include <QBrush>
#include <QRect>

PreviewScr::PreviewScr(QWidget *parent, int num) :
    QWidget(parent),
    screenNum(num)
{
    init();
}

PreviewScr::PreviewScr(QWidget *parent, QWidget *scr, int num) :
    QWidget(parent),
    screen(scr),
    screenNum(num)
{
    //TODO
    init();
}

void PreviewScr::init(){
    this->setContextMenuPolicy(Qt::ActionsContextMenu);
    actDrawImage = new QAction(tr("Show Image"), this);
    connect(actDrawImage, SIGNAL(triggered()), SLOT(sendDrawImage()));
    this->addAction(actDrawImage);

    actShowClock = new QAction(tr("Show Clock"), this);
    connect(actShowClock, SIGNAL(triggered()), SLOT(sendShowClock()));
    this->addAction(actShowClock);
}

void PreviewScr::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e);

    QPixmap newMap = QPixmap::grabWindow(screen->winId());
    double wVactor = (double) screen->width() / (double) PREVIEWWIDTH;
    double hVactor = (double) screen->height() / (double) PREVIEWHEIGHT;
    newMap = wVactor > hVactor ?
                newMap.scaledToWidth(PREVIEWWIDTH) :
                newMap.scaledToHeight(PREVIEWHEIGHT);
    QImage newImage = newMap.toImage();
    QPainter painter(this);
    QPen pen;
    QBrush brush;

    brush.setTexture(newMap);
//    brush.setTexture(QPixmap("D:/My/Dropbox/Gui Programs/MultiDisplay/mhnikki.JPG"));
    pen.setStyle(Qt::NoPen);

    painter.setBrush(brush);
    painter.setPen(pen);
    int left = (PREVIEWWIDTH - newMap.width()) / 2.0;
    int top = (PREVIEWHEIGHT - newMap.height()) / 2.0;
    painter.drawImage(left, top, newImage);
}

void PreviewScr::focusInEvent(QFocusEvent *)
{
    this->setAutoFillBackground(true);
    QPalette palette;
    palette.setColor(QPalette::Background, Qt::white);
    this->setPalette(palette);
}

void PreviewScr::focusOutEvent(QFocusEvent *)
{
    this->setAutoFillBackground(false);
}

void PreviewScr::sendDrawImage()
{
    emit drawImage(screenNum);
}

void PreviewScr::sendShowClock()
{
    emit showClock(screenNum);
}
